<template>
  <div>

    <van-cell-group>
      <van-field v-model="publishForm.title" label="文本" placeholder="标题" />
      <van-field
        v-model="publishForm.content"
        label="内容"
        placeholder="内容"
      />
    </van-cell-group>

    <van-field
      readonly
      clickable
      name="picker"
      :value="publishForm.cate_name"
      label="选择分类"
      placeholder="点击选择分类"
      @click="showPicker = true"
    />
    <van-popup v-model="showPicker" position="bottom">
      <van-picker
        show-toolbar
        :columns="cateList"
        value-key="name"
        @confirm="onCatePickerConfirm"
        @cancel="showPicker = false"
      />
    </van-popup>

    <van-uploader v-model="fileList" :max-count="3" multiple />
    <van-button @click="publish">发布</van-button>
  </div>
</template>

<script>
import { Field, Picker, Popup, Uploader } from "vant";
import { mapState } from "vuex";

import { uploadFile } from "@/api/upload";
import { add_article } from "@/api/publish";

export default {
  name: "PublishView",
  data() {
    return {
      a:100,
      publishForm: {
        title: "",
        content: "",
        cate_id: "",
        cate_name: "",
        author: "",
        author_id: "",
        imageSrc: [],
      },
      fileList: [],
      showPicker: false,
    };
  },
  computed: {
    ...mapState("cate", ["cateList"]),
    ...mapState("user", ["uid", "userInfo"]),
  },
  components: {
    [Field.name]: Field,
    [Picker.name]: Picker,
    [Popup.name]: Popup,
    [Uploader.name]: Uploader,
  },
  methods: {
    async publish() {
      let { uid, userInfo, publishForm, fileList } = this;
      if (!uid) {
        this.$toast("请先登陆");

        setTimeout(() => {
          this.$router.push("/login");
        }, 1000);
        return;
      }

      publishForm.author = userInfo.nickname;
      publishForm.author_id = uid;

      if (fileList.length == 2) {
        this.$toast("请上传一张或者三张");
        return;
      }

      if (fileList.length > 0) {
        let task = fileList.map((v, k) => {
          return uploadFile(fileList[k].file);
        });
        publishForm.imageSrc = await Promise.all(task);
      }

      add_article(publishForm).then((res) => {
        console.log(res);
      });
    },
    //  onCatePickerConfirm   分类picker确认时
    onCatePickerConfirm({ name, _id }) {
      this.showPicker = false;
      this.publishForm.cate_id = _id;
      this.publishForm.cate_name = name;
    },
  },
};
</script>

<style >

</style>
